//
//  MySelfTableViewController.m
//  HYSmileiOS
//
//  Created by alekye on 16/4/24.
//  Copyright © 2016年 heyou. All rights reserved.
//

#import "MySelfTableViewController.h"
#import "heyou.h"
#import "UserManager.h"
#import "LoginHeaderCell.h"
#import "LoginHeaderTipCell.h"
#import "LoginNaviController.h"
#import "HYNotifications.h"
#import "MainTableViewController.h"

#define ITEM_HEADER     @"用户信息"

#define ITEM_MYWEIBO    @"我发的图"
#define ITEM_MYCOMMENT  @"我评论的"
#define ITEM_MYLIKE     @"我赞过的"
#define ITEM_MYHATE     @"我踩过的"

#define ITEM_EXIT       @"退出"

@interface MySelfTableViewController ()

@property (strong, nonatomic) NSArray<NSArray*>* mLoginItemList;

@end

@implementation MySelfTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    [self setupNotification];
    [self prepareData];
    [self setupTable];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark -- prepare data
- (void)prepareData {
    NSArray *info = @[ITEM_HEADER];
    NSArray *items = @[ITEM_MYWEIBO, ITEM_MYCOMMENT, ITEM_MYLIKE, ITEM_MYHATE];
    NSArray *exit = @[ITEM_EXIT];
    NSArray *list = @[info, items, exit];
    self.mLoginItemList = list;
}

#pragma mark -- Notification
- (void)setupNotification {
    NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
    [defaultCenter addObserver:self selector:@selector(onLoginSucess:) name:USER_LOGIN_SUCCESS object:nil];
    [defaultCenter addObserver:self selector:@selector(onLoginFailure:) name:USER_LOGIN_FAILURE object:nil];
    [defaultCenter addObserver:self selector:@selector(onLogoutDone:) name:USER_LOGOUT_DONE object:nil];
}

- (void)onLoginSucess:(NSNotification*)notify {
    [self updateUI];
}

- (void)onLoginFailure:(NSNotification*)notify {
    [self updateUI];
}

- (void)onLogoutDone:(NSNotification*)notify {
    [self updateUI];
}

- (void)dealloc {
    NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
    [defaultCenter removeObserver:self];
}

#pragma mark -- setup table
- (void)setupTable {
    // 注册XIB
    [XibUtils registXibCell:[LoginHeaderCell class] toTable:self.tableView];
    [XibUtils registXibCell:[LoginHeaderTipCell class] toTable:self.tableView];
    self.tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, CGFLOAT_MIN)];
    self.tableView.tableFooterView = [UIView new];
}

- (void)updateUI {
    [self.tableView reloadData];
}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    NSInteger num = 0;
    
    if ([[UserManager sharedInstance] isUserLogin]) {
        // 用户已登录
        num = self.mLoginItemList.count;
    } else {
        // 用户未登录
        num = 1;
    }
    
    return num;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSInteger num = 0;
    
    if ([[UserManager sharedInstance] isUserLogin]) {
        // 用户已登录
//        num = self.mLoginItemList.count;
        NSArray *items = [self.mLoginItemList objectAtIndex:section];
        num = items.count;
    } else {
        // 用户未登录
        num = 1;
    }
    
    return num;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    CGFloat height = 0.0f;
    
    if ([[UserManager sharedInstance] isUserLogin]) {
        // 用户已登录
        NSArray *items = [self.mLoginItemList objectAtIndex:indexPath.section];
        NSString *title = [items objectAtIndex:indexPath.row];
        if ([title isEqualToString:ITEM_HEADER]) {
            height = 80.0f;
        } else {
            
        }
    } else {
        // 用户未登录
        height = self.view.frame.size.height - 64.0f - 49.0f;
    }
    
    height = MAX(height, 45.0f);
    return height;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    CGFloat height = 0.0f;
    
    if ([[UserManager sharedInstance] isUserLogin]) {
        // 用户已登录
        if (section == 0) {
            
        } else {
            height = 10.0f;
        }
    } else {
        // 用户未登录
    }
    
    return height;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return CGFLOAT_MIN;
}

#pragma mark -- config tableview
- (void)configCell:(UITableViewCell*)cell forIndex:(NSIndexPath*)indexPath {
    if ([[UserManager sharedInstance] isUserLogin]) {
        // 用户已登录
        NSArray *items = [self.mLoginItemList objectAtIndex:indexPath.section];
        NSString *title = [items objectAtIndex:indexPath.row];
        if ([title isEqualToString:ITEM_HEADER]) {
            LoginHeaderCell *tCell = (LoginHeaderCell*)cell;
//            tCell.labelTitle.text = @"天数微博From";
            UserInfoDetail *info = [[UserManager sharedInstance] getCurrentUser];
            tCell.labelTitle.text = info.nickname;
            tCell.labelId.text = [NSString stringWithFormat:@"ID: %ld", info.uid];
            UIImage *placeHolder = [UIImage imageNamed:@"img_header_default"];
            NSString *fURL = info.headimgurl;
            NSURL *tURL = [NSURL URLWithString:fURL];
            [tCell.imageViewHeader sd_setImageWithURL:tURL placeholderImage:placeHolder];
        } else {
            cell.textLabel.text = title;
            cell.detailTextLabel.text = @"123";
        }
    } else {
        // 用户未登录
        LoginHeaderTipCell *tCell = (LoginHeaderTipCell*)cell;
        tCell.labelTip.text = @"您还没有登录\r\n\r\n登录后可进行评论，收藏等操作";
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = nil;
    
    if ([[UserManager sharedInstance] isUserLogin]) {
        // 用户已登录
        NSArray *items = [self.mLoginItemList objectAtIndex:indexPath.section];
        NSString *title = [items objectAtIndex:indexPath.row];
        if ([title isEqualToString:ITEM_HEADER]) {
            NSString *identifier = NSStringFromClass([LoginHeaderCell class]);
            LoginHeaderCell *tCell = [tableView dequeueReusableCellWithIdentifier:identifier forIndexPath:indexPath];
            tCell.imageViewHeader.layer.masksToBounds = YES;
            tCell.imageViewHeader.layer.cornerRadius = tCell.imageViewHeader.frame.size.height/2.0f;
            cell = tCell;
        } else {
            NSString *identifier = @"MY_ITEM_DEFAULT";
            UITableViewCell *tCell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:identifier];
            tCell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            
            cell = tCell;
        }
    } else {
        // 用户未登录
        NSString *identifier = NSStringFromClass([LoginHeaderTipCell class]);
        LoginHeaderTipCell *tCell = [tableView dequeueReusableCellWithIdentifier:identifier forIndexPath:indexPath];
        WS(ws);
        [tCell.buttonLogin handleControlEvent:UIControlEventTouchUpInside withBlock:^(UIButton *sender) {
            UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"Login" bundle:nil];
            NSString *identifier = NSStringFromClass([LoginNaviController class]);
            LoginNaviController *vc = [storyBoard instantiateViewControllerWithIdentifier:identifier];
            [ws presentViewController:vc animated:YES completion:nil];
        }];
        
        cell = tCell;
    }
    
    // Configure the cell...
    [self configCell:cell forIndex:indexPath];
    
    return cell;
}

/**
 *  跳转到列表页
 *
 *  @param listType 列表类型
 */
- (void)gotoArticleController:(ListArticleType)listType title:(NSString*)title{
    UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"Home" bundle:nil];
    NSString *identifier = NSStringFromClass([MainTableViewController class]);
    MainTableViewController *vc = [storyBoard instantiateViewControllerWithIdentifier:identifier];
    vc.title = title;
    vc.listType = listType;
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark -- table delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    
    if ([[UserManager sharedInstance] isUserLogin]) {
        // 用户已登录
        NSArray *items = [self.mLoginItemList objectAtIndex:indexPath.section];
        NSString *title = [items objectAtIndex:indexPath.row];
        if ([title isEqualToString:ITEM_HEADER]) {
            
        } else if ([title isEqualToString:ITEM_MYWEIBO]) {
            [self gotoArticleController:ListArticleType_MyArticle title:title];
        } else if ([title isEqualToString:ITEM_MYCOMMENT]) {
            [self gotoArticleController:ListArticleType_Comment title:title];
        } else if ([title isEqualToString:ITEM_MYLIKE]) {
            [self gotoArticleController:ListArticleType_Like title:title];
        } else if ([title isEqualToString:ITEM_MYHATE]) {
            [self gotoArticleController:ListArticleType_Hate title:title];
        } else if ([title isEqualToString:ITEM_EXIT]) {
            // ios 8.0
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"确定要退出当前账号？" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                NSLog(@"cancel ----");
            }];
            UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                NSLog(@"ok, exit ----");
                [[UserManager sharedInstance] userLogout];
            }];
            [alertController addAction:cancelAction];
            [alertController addAction:okAction];
            [self presentViewController:alertController animated:YES completion:nil];
        }
    } else {
        // 用户未登录
    }
}

@end
